package com.harvest.scientific.ladder.page.fa

import android.graphics.Color
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.harvest.scientific.ladder.R
import com.harvest.scientific.ladder.base.BaseFragment
import com.harvest.scientific.ladder.constant.PageArgs
import com.harvest.scientific.ladder.databinding.FragmentAmountSelectBinding
import com.harvest.scientific.ladder.dialog.AmountSelectedPopup
import com.harvest.scientific.ladder.dialog.OrderSuccessAdapter
import com.harvest.scientific.ladder.dialog.OrderSuccessDialog
import com.harvest.scientific.ladder.ext.countDown
import com.harvest.scientific.ladder.ext.dp2px
import com.harvest.scientific.ladder.ext.formatToNumber
import com.harvest.scientific.ladder.ext.getCurDate
import com.harvest.scientific.ladder.ext.notEmpty
import com.harvest.scientific.ladder.ext.setMaterialDrawable
import com.harvest.scientific.ladder.ext.toHtml
import com.harvest.scientific.ladder.page.HomeActivity
import com.harvest.scientific.ladder.page.LoginActivity
import com.harvest.scientific.ladder.page.adapter.TermAdapter
import com.harvest.scientific.ladder.res.JustUndividedPartBath
import com.harvest.scientific.ladder.res.MentalDrinkRes
import com.harvest.scientific.ladder.res.QueryProMissRes
import com.harvest.scientific.ladder.res.StrongPensionQuilt
import com.harvest.scientific.ladder.util.LogUtils
import com.harvest.scientific.ladder.util.ToastUtil
import com.harvest.scientific.ladder.util.VcUtil
import com.harvest.scientific.ladder.util.isLogin
import com.harvest.scientific.ladder.widget.BaseActionBar
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import java.math.BigDecimal


/**
 * A simple [Fragment] subclass.
 * Use the [AmoutSelectFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class AmountSelectFragment : BaseFragment<FragmentAmountSelectBinding>() {

    private lateinit var countDownJob: Job
    private var _queryProMissRes: QueryProMissRes? = null
    private val viewModel by viewModels<AmountViewModel>({ requireActivity() })
    private var sA = ""
    private var menRes: MentalDrinkRes? = null

    override fun initPage() {
        super.initPage()
        viewModel
        _binding.scrollView.setMaterialDrawable(dp2px(20f), Color.WHITE)
        loadData()
        initListener()
        initView()

    }

    private val planList = arrayListOf<StrongPensionQuilt>()

    private fun initView() {
        _binding.planRv.adapter = OrderSuccessAdapter(planList, 1).also { planAdapter = it }
    }

    private val amountPopList = arrayListOf<String>()

    private fun initListener() {

        _binding.amountSelectContainer.setOnClickListener {
            if (VcUtil.isFastDoubleClick(it)) {
                return@setOnClickListener
            }
            var amountPopup: AmountSelectedPopup? = null
            AmountSelectedPopup(requireActivity(), amountPopList) { adapter, view, pos ->
                sA = amountPopList[pos]
                _queryProMissRes?.let {
                    viewModel.mentalDrinkDryerDouble(
                        it.usefulTailChocolate,
                        proList[termIndex].thirstyHousewifeBoxTomato,
                        sA.replace(",", "")
                    )
                }
                updateAmountUi()
                amountPopup?.dismiss()
            }

                .setBackground(null)
                .also { amountPopup = it as? AmountSelectedPopup? }
                .showPopupWindow(_binding.amountSelectContainer)
        }

        _binding.applyBtn.setOnClickListener {
            if (VcUtil.isFastDoubleClick(it)) {
                return@setOnClickListener
            }
            _queryProMissRes?.let {
                showLoading()
                viewModel.chiefPepperHumourKid(
                    it.usefulTailChocolate,
                    proList[termIndex].thirstyHousewifeBoxTomato,
                    sA.replace(",", "")
                )
            }
        }
        lifecycleScope.launch {
            launch {
                viewModel.chiefPepperHumourKid.collect {res->
                    dismissLoading()
                    LogUtils.d("chiefPepperHumourKid res ->$res")
                    if (res.customData.notEmpty()) {
                        ToastUtil.showToast(res.customData)
                    } else {
                        OrderSuccessDialog(requireActivity(),planList) {
                            HomeActivity.jump(requireActivity(), 0)
                        }.show()
                    }
                }
            }
            launch {
                viewModel.queryProMissFlow.collect { res ->
                    handleQueryProMiss(res)
                }
            }
            launch {
                viewModel.mentalDrinkRes.collect { res ->
                    var minRA = BigDecimal.valueOf(0.0)
                    LogUtils.d("minRA -> $minRA, clickPos:$clickPos, termIndex:$termIndex")

                    res.strongPensionQuilt.forEach {
                        val temp = BigDecimal.valueOf(it.thankfulRainyLung)
                        if (temp < minRA || minRA == BigDecimal.valueOf(0.0)) {
                            minRA = temp
                        }

                    }
                    if (proList[clickPos].type == 1) {
                        ToastUtil.showToast(
                            getString(
                                R.string.term_zuidi_info,
                                minRA.multiply(BigDecimal.valueOf(0.8))
                            )
                        )
                    } else {
                        planList.clear()
                        planList.addAll(res.strongPensionQuilt)
                        planAdapter.notifyDataSetChanged()
                        menRes = res
                        // update pre amount
                        updatePreAmount()
                    }
                    clickPos = termIndex
                }

            }
            launch {
                countDownJob = countDown(time = 60 * 10, next = {
                    updateTime(it)
                }, end = {
                    updateTime(0)
                })
            }
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        countDownJob.cancel()
    }

    private fun updateTime(count: Int) {
        val minute = count / 60
        val second = count % 60

        val showTime = if (count != 0) "${minute}:$second" else "0"
        _binding.tipTextTv.text = getString(R.string.cliquez_demander_avant_99_approuv, showTime).toHtml()
    }

    private fun updatePreAmount() {
        LogUtils.d("updatePreAmount")
        menRes?.let {menRes->
            _binding.remboursementTv.text = menRes.moreDeerFamousFarmContinent.toString().formatToNumber()?.toXof()
            _binding.montantTv.text = menRes.considerateFrance.toString().formatToNumber()?.toXof()
            _binding.lixiTv.text = menRes.changeableFuneralAboveInstrumentMadScream.toString().formatToNumber()?.toXof()
            _binding.serviceTv.text = menRes.cloudyToothLaw.toString().formatToNumber()?.toXof()
            _binding.taxeTv.text = menRes.doubleMotorcycleDueDepth.toString().formatToNumber()?.toXof()
        }
    }

    private fun String.toXof() = requireActivity().getString(R.string.xof, this)

    private fun updateAmountUi() {
        val amount = getString(R.string.xof, sA)
        _binding.selectedAmountTv2.text = amount
        _binding.selectedAmountTv.text = amount
        _binding.montant2Tv.text = amount

    }

    private var proList = arrayListOf<JustUndividedPartBath>()

    private fun handleQueryProMiss(res: QueryProMissRes) {
        _queryProMissRes = res
        val justList = res.justUndividedPartBath

        if (justList.notEmpty()) {
            proList.addAll(justList)
            val maxTerm = proList.maxOf { it.antarcticPig }
//            val lastDays = pList.last().antarcticPig * pList.last().puzzledLoudSpecialist
            proList.add(JustUndividedPartBath(type = 1, antarcticPig = maxTerm + 1, puzzledLoudSpecialist = proList.first().puzzledLoudSpecialist))
            proList.add(JustUndividedPartBath(type = 1, antarcticPig = maxTerm + 2, puzzledLoudSpecialist = proList.first().puzzledLoudSpecialist))

            updateAmountList(0)

            _queryProMissRes?.let {
                viewModel.mentalDrinkDryerDouble(
                    it.usefulTailChocolate,
                    proList[termIndex].thirstyHousewifeBoxTomato,
                    sA.replace(",", "")
                )
            }

            setTermAdapter(proList)
            _binding.timeTv.text = getCurDate()

        }

    }

    private fun updateAmountList(index: Int) {
        val index0 = proList[index]
        val amountList = calculatorAmountList(index0)
        LogUtils.d("amoutList  ->> $amountList")
        if (amountList.notEmpty()) {
            amountPopList.clear()
            amountPopList.addAll(amountList)
            sA = amountList.first()
            updateAmountUi()
        }
    }

    private lateinit var termAdapter: TermAdapter
    private lateinit var planAdapter: OrderSuccessAdapter
    private var termIndex = 0
    private var clickPos = 0

    private fun setTermAdapter(pList: List<JustUndividedPartBath>) {
        if (pList.notEmpty()) {
            pList.first().selected = true
            _binding.termRv.adapter = TermAdapter().also {
                termAdapter = it
                it.setOnItemClickListener{ adapter, view ,pos ->
                    if (clickPos == pos) {
                        return@setOnItemClickListener
                    }
                    clickPos = pos
                    _queryProMissRes?.let {
                        viewModel.mentalDrinkDryerDouble(
                            it.usefulTailChocolate,
                            proList[termIndex].thirstyHousewifeBoxTomato,
                            sA.replace(",", "")
                        )
                        if (proList[pos].type == 0) {
                            proList.forEach {
                                it.selected = false
                            }
                            termIndex = pos
                            proList[pos].selected = true
                            adapter.notifyDataSetChanged()
                            updateAmountList(pos)
                        }
                    }
                }
            }
            termAdapter.addAll(pList)
        }
    }

    private fun calculatorAmountList(index0: JustUndividedPartBath): List<String> {
        val amountList = arrayListOf<BigDecimal>()
        val maxA = BigDecimal.valueOf(index0.prettyCrazyHerb)
        var minA = BigDecimal.valueOf(index0.slimImpossibleJuicyDad)
        val increA = BigDecimal.valueOf(index0.freezingMagicSpain)


        if (maxA.compareTo(minA) != 0) {

            while (minA < maxA) {
                amountList.add(minA)
                minA = minA.add(increA)
            }
        }
        amountList.add(maxA)
        amountList.reverse()
        return amountList.map { it.toString().formatToNumber(',') ?: "" }
    }

    override fun onResume() {
        super.onResume()

    }

    override fun loadData() {
        viewModel.queryProMissRes()
    }

    override fun setStatus(actionBar: BaseActionBar) {
        super.setStatus(actionBar)
        actionBar.apply {
            isShowBusinessServer(false)
            setTitle(getString(R.string.app_name))
            setVisible(true)
            setBackListener {
                requireActivity().finish()
            }
        }
    }

    override fun isShowBg(): Boolean {
        return true
    }

    companion object {

        @JvmStatic
        fun newInstance() =
            AmountSelectFragment().apply {
                arguments = Bundle().apply {
                }
            }
    }
}